package com.bite.gateway.filter;

import com.bite.common.pojo.Result;
import com.bite.common.utils.JWTUtils;
import com.bite.gateway.properties.AuthWhiteName;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
//    private final List<String> whiteNames = List.of("/user/login","/user/register");

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    AuthWhiteName authWhiteName;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (authWhiteName.getUrl().contains(path)){
            return chain.filter(exchange);
        }

        String user_token = request.getHeaders().getFirst("user_token");
        if (!StringUtils.hasText(user_token)){
            return unauthorizedResponse(exchange, "令牌不能为空");
        }

        Claims claims = JWTUtils.parseJWT(user_token);
        if (claims == null) {
            return unauthorizedResponse(exchange, "令牌超时或不合法");
        }

        return chain.filter(exchange);
    }

    @SneakyThrows
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String errMag) {
        log.error("[用户认证失败]，url: {}", exchange.getRequest().getURI().getPath());
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        Result fail = Result.fail(errMag);
        DataBuffer wrap = response.bufferFactory().wrap(objectMapper.writeValueAsBytes(fail));
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
